//
//  APVideosViewController.m
//  AqualPolo
//
//  Created by dong on 2024/5/1.
//

#import "APVideosViewController.h"
#import "APVideoDataManager.h"
#import "APVideoDetailViewController.h"
#import "APBottomMenuViewController.h"
#import "APUserDataManager.h"
#import "VideoRecorderController.h"
#import <AVFoundation/AVFoundation.h>
#import "APLoginManager.h"
#import "APHomeDataManager.h"
#import "APQiCardView.h"
#import "APCardStackAnimationCell.h"
#import "APUnlockAlertViewController.h"

@interface APVideosViewController ()<QiCardViewDataSource, QiCardViewDelegate>
@property (nonatomic, strong) UIImageView *topImageView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UIButton *cameraButton;
@property (nonatomic, strong) APQiCardView *cardView;//!< 主角：QiCardView
@property (nonatomic, strong) APVideoModel *currentVideoModel;
@property (nonatomic, assign) bool autoFix;

@end

@implementation APVideosViewController

- (APQiCardView *)cardView{
    if (!_cardView) {
        _cardView = [[APQiCardView alloc] initWithFrame:CGRectMake(25.0, 150.0, self.view.frame.size.width - 50.0, 420.0)];
        _cardView.backgroundColor = [UIColor clearColor];//!< 为了指出carddView的区域，指明背景色
        _cardView.dataSource = self;
        _cardView.delegate = self;
        _cardView.visibleCount = 3;
        _cardView.lineSpacing = 15.0;
        _cardView.interitemSpacing = 20.0;
        _cardView.maxAngle = 10.0;
        _cardView.isAlpha = YES;
        _cardView.maxRemoveDistance = 100.0;
        _cardView.layer.cornerRadius = 8;
        [_cardView registerClass:[APCardStackAnimationCell class] forCellReuseIdentifier:@"card"];
        [self.view addSubview:_cardView];
    }
    return _cardView;
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (UILabel *)titleLabel{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.textColor = [UIColor whiteColor];
        _titleLabel.font = [LYFont fontWithSize:24 fontName:LYFontNamepfr];
        _titleLabel.textAlignment = NSTextAlignmentLeft;
        _titleLabel.text = @"Video";
    }
    return _titleLabel;
}

- (UIButton *)cameraButton{
    if (!_cameraButton) {
        _cameraButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_cameraButton setBackgroundImage:[UIImage imageNamed:@"camera_icon"] forState:UIControlStateNormal];
        [_cameraButton addTarget:self action:@selector(cameraButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cameraButton;
}



- (UIImageView *)topImageView{
    if (!_topImageView) {
        _topImageView = [[UIImageView alloc] init];
        _topImageView.image = [UIImage imageNamed:@"table_header_icon"];
    }
    return _topImageView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadBackground:@"discovery_list_bg"];
    _autoFix = true;
    [self initUI];
}

- (void)cameraButtonDidClick:(UIButton *)sender{
    
    VideoRecorderController *videoRecorderVC = [[VideoRecorderController alloc] init];
    [videoRecorderVC recordVideoFinishedBlock:^(NSURL *fileUrl, NSString *fileName) {
        [self saveVideoFile:fileName videoURL:fileUrl];
    }];
    [self presentViewController:videoRecorderVC animated:true completion:nil];
    
}

- (void)saveVideoFile:(NSString *)videoName videoURL:(NSURL *)videoURL{
    [self.view ShowProgress];
    /// 网络地址    /// 本地文件
    NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:videoURL options:opts];
    AVAssetImageGenerator *assetImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    NSError *error = nil;
    CGImageRef thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(0, 1) actualTime:NULL error:&error];
    if( error ) {
        LYLog(@"===first image===%@", error );
    }
    UIImage *image = nil;
    if(thumbnailImageRef) {
        image =  [[UIImage alloc]initWithCGImage:thumbnailImageRef];
    }
    NSString *imageName = [BaseDataManager saveImageWithData:image toFile:images_path imageName:@"cover"];
    APVideoModel *model = [[APVideoModel alloc] init];
    APUserModel *userModel = [[APLoginManager shareInstance] userInfo];
    model.userId = userModel.userId;
    model.avatar = userModel.avatarUrl;
    model.nickname = userModel.nickname;
    model.isCreate = YES;
    model.mediaUrl = videoName;
    model.middleThumbUrl = imageName;
//    model.content = content;
//    model.title = title;
    model.isBlack = NO;
    WS(ws);
    _autoFix = false;
    [[APVideoDataManager shareInstance] initVideoData:^(NSArray * _Nonnull videos) {
        [[APVideoDataManager shareInstance] addVideo:model];
        [ws.view removeProgress];
        [ws refreshData:false];
        [self showAlert];
    }];
 
}

- (void)showAlert{
    if (![[APHomeDataManager shareInstance] isBallUnlock:APBallTypeSeniorDominator]) {
        [[APHomeDataManager shareInstance] unlockBall:APBallTypeSeniorDominator];
        APUnlockAlertViewController *alertVC = [[APUnlockAlertViewController alloc] init];
        alertVC.ballType = APBallTypeSeniorDominator;
        [self presentViewController:alertVC animated:true completion:nil];
    }
}



- (void)refreshData:(BOOL)fix{
    [self.view ShowProgress];
    [self.dataArray removeAllObjects];
    WS(ws);
    [[APVideoDataManager shareInstance] initVideoData:^(NSArray * _Nonnull videos) {
        for (APVideoModel *model in videos) {
            APBroadcasterModel *userModel = [[APUserDataManager shareInstance] searchUserByUserId:model.userId];
            model.isFollow = userModel.isFriend;
            if (!model.isBlack) {
                if (fix && ws.currentVideoModel && [ws.currentVideoModel.mediaUrl isEqualToString:model.mediaUrl]) {
                    [self.dataArray insertObject:model atIndex:0];
                }else{
                    [ws.dataArray addObject:model];
                }
            }
        }
        [ws.cardView reloadData];
        [ws.view removeProgress];
        self.autoFix = true;
    }];
}


- (APQiCardViewCell *)cardView:(APQiCardView *)cardView cellForRowAtIndex:(NSInteger)index {
    APCardStackAnimationCell *cell = [cardView dequeueReusableCellWithIdentifier:@"card"];
    cell.model = self.dataArray[index];
    cell.index = index;
    [cell.upvoteButton addTarget:self action:@selector(upvoteButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [cell.moreButton addTarget:self action:@selector(moreButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [cell.coverImageButton addTarget:self action:@selector(playButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];

    return cell;
}


- (void)upvoteButtonDidClick:(UIButton *)sender{
    APCardStackAnimationCell *cell = (APCardStackAnimationCell *)sender.superview.superview;
    NSInteger index = cell.index;
    APVideoModel *videoModel = self.dataArray[index];
    videoModel.isUpvote = !videoModel.isUpvote;
    [[APVideoDataManager shareInstance] updateVideo];
    [self refreshData:true];
}

- (void)moreButtonDidClick:(UIButton *)sender{
    APCardStackAnimationCell *cell = (APCardStackAnimationCell *)sender.superview.superview;
    NSInteger index = cell.index;
    APVideoModel *videoModel = self.dataArray[index];
    APBottomMenuViewController *menuVC = [[APBottomMenuViewController alloc] init];
    [menuVC setCallBack:^(NSInteger index) {
        [self refreshData:true];
    }];
    menuVC.userId = videoModel.userId;
    [self.tabBarController presentViewController:menuVC animated:true completion:nil];
}

- (void)playButtonDidClick:(UIButton *)sender{
    APCardStackAnimationCell *cell = (APCardStackAnimationCell *)sender.superview.superview;
    NSInteger index = cell.index;
    APVideoModel *videoModel = self.dataArray[index];
    APVideoDetailViewController *videoDetailVC = [[APVideoDetailViewController alloc] init];
    videoDetailVC.videoModel = videoModel;
    videoDetailVC.hidesBottomBarWhenPushed = true;
    [self.navigationController pushViewController:videoDetailVC animated:false];

    
}

- (NSInteger)numberOfCountInCardView:(UITableView *)cardView {
    return self.dataArray.count;
}


#pragma mark - QiCardViewDelegate

- (void)cardView:(APQiCardView *)cardView didRemoveLastCell:(APQiCardViewCell *)cell forRowAtIndex:(NSInteger)index {
    [cardView reloadDataAnimated:YES];
}

- (void)cardView:(APQiCardView *)cardView didRemoveCell:(APQiCardViewCell *)cell forRowAtIndex:(NSInteger)index {
    LYLog(@"didRemoveCell forRowAtIndex = %ld", index);
}

- (void)cardView:(APQiCardView *)cardView didDisplayCell:(APQiCardViewCell *)cell forRowAtIndex:(NSInteger)index {
    APVideoModel *videoModel = self.dataArray[index];
    _currentVideoModel = videoModel;

    LYLog(@"didDisplayCell forRowAtIndex = %ld", index);
    
    LYLog(@"currentFirstIndex = %ld",cardView.currentFirstIndex);
    LYLog(@"%ld",index);
    
    
}

- (void)cardView:(APQiCardView *)cardView didMoveCell:(APQiCardViewCell *)cell forMovePoint:(CGPoint)point {
//    NSLog(@"move point = %@", NSStringFromCGPoint(point));
}




- (void)initUI{
    [self.view addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(30);
        make.left.equalTo(self.view).offset(20);
    }];
    [self.view addSubview:self.topImageView];
    [self.topImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLabel.mas_bottom).offset(10);
        make.left.equalTo(self.view).offset(20);
        make.size.mas_equalTo(CGSizeMake(79, 70));
    }];
    
    [self.view addSubview:self.cameraButton];
    [self.cameraButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-19);
        make.centerY.equalTo(self.titleLabel.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(43, 29));
    }];
    
    [self.view addSubview:self.cardView];
    [self.cardView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topImageView).offset(47);
        make.left.equalTo(self.view).offset(12);
        make.right.equalTo(self.view).offset(-12);
        make.bottom.equalTo(self.view).offset(-80);
    }];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = true;
    if (_autoFix) {
        [self refreshData:true];
    }

}

- (void)viewSafeAreaInsetsDidChange{
    [super viewSafeAreaInsetsDidChange];
    CGFloat top = self.view.safeAreaInsets.top > 0 ? self.view.safeAreaInsets.top:20;
    [self.titleLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(10 + top);
    }];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
  
    }
    return  self;
}

@end
